#include<iostream>
#include<pthread.h>
#include<vector>
#include<semaphore.h>
using namespace std;
#define N 5

template<class T>
class RQueue
{
public:
    RQueue(int n = N):_v(n)
    {}
    void Init()
    {
        sem_init(&_pro,0,_v.size());
        sem_init(&_con,0,0);
        pthread_mutex_init(&_pmutex,nullptr);
        pthread_mutex_init(&_cmutex,nullptr);
    }
    void push(const T&date)
    {
        sem_wait(&_pro);
        pthread_mutex_lock(&_pmutex);
        _v[_pstep++] = date;
        _pstep%=_v.size();
        pthread_mutex_unlock(&_pmutex);
        sem_post(&_con);

    }
    T pop()
    {
        sem_wait(&_con);
        pthread_mutex_lock(&_cmutex);
        T date =_v[_cstep++];
        _cstep%=_v.size();
        pthread_mutex_unlock(&_cmutex);
        sem_post(&_pro);
        return date;
    }
    ~RQueue()
    {
        sem_destroy(&_pro);
        sem_destroy(&_con);
        pthread_mutex_destroy(&_pmutex);
        pthread_mutex_destroy(&_cmutex);
    }
private:
    sem_t _pro;
    sem_t _con;
    vector<T>_v;
    pthread_mutex_t _pmutex;
    pthread_mutex_t _cmutex;
    int _pstep;
    int _cstep;
};
